package pe.com.ValoracionVivienda.service.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import pe.com.ValoracionVivienda.service.interfaces.GenericService;

public abstract class GenericServiceJpaImpl<K, E> implements GenericService<K, E> {

	protected Class<E> entityClass;
	protected EntityManager em;
	protected EntityManagerFactory emf;
	
	@SuppressWarnings("unchecked")
	public GenericServiceJpaImpl() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
		this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
		
		emf = Persistence.createEntityManagerFactory("ValoracionViviendaPU");
		em = emf.createEntityManager();
	}
	
	@Override
	public E persist(E entity) { em.persist(entity); return entity;}

	@Override
	public void remove(E entity) { em.remove(entity); }

	@Override
	public E findById(K id) { return em.find(entityClass, id); }	
	
	@Override
	public E update(E t){ return em.merge(t); }
	
	@Override
	public List<E> findAll(){
		return em.createQuery("SELECT e FROM " + entityClass.getName() + " e", entityClass).getResultList();
	}
	
	@Override
	public EntityTransaction getTransaction(){ return em.getTransaction(); }
	
	@Override
	public void close(){
		if (em != null)
			em.close();
		
		if (emf != null)
			emf.close();
	}
}
